const express = require('express')
const multer  = require('multer')
const path    = require('path')
const fs      = require('fs')
const router  = express.Router()

// 1. 确保目录存在
const UPLOAD_DIR = path.resolve(__dirname, '../../public/uploads')
if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR, { recursive: true })

// 2. multer 配置：文件名 + 存放路径
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, UPLOAD_DIR),
  filename:    (req, file, cb) => {
    const ext = path.extname(file.originalname)          // .jpg
    const name = Date.now() + Math.round(Math.random() * 1e9) + ext
    // const name = Date.now() + '-' + Math.round(Math.random() * 1e9) + ext
    cb(null, name)
  }
})
const upload = multer({ storage })

// 3. 把 /public 设为静态目录，前端才能 http://localhost:3000/uploads/xxx.jpg 访问
router.use('/public', express.static(path.join(__dirname, 'public')))

// 4. 上传接口
router.post('/upload/logo', upload.single('logo'), (req, res) => {
  // req.file 就是上传的文件信息
  if (!req.file) return res.status(400).json({ msg: '未上传文件' })
  // const fileUrl = `/public/uploads/${req.file.filename}`   // 返回给前端的可访问地址
  const fileUrl = `http://localhost:3000/uploads/${req.file.filename}`   // 返回给前端的可访问地址
  res.json({ url: fileUrl })
})

module.exports = router